import { computed, defineComponent, ref, unref, watch } from '@vue/runtime-core';
import { Input, Modal, AutoComplete, Button, Divider } from 'ant-design-vue';
import { getMyIntention, commitMyIntention, intentionRef } from '/@/hooks/usePages';
import { appStore } from '/@/store/modules/app';

export default defineComponent({
  name: 'intentionPetition',
  setup() {
    const visible = ref(false);
    const editKey = ref(-1);
    const editValue = ref('');
    const defaultIntention: string[] = [
      '尤其助我（们）早日渡过当前的难关；',
      '给（名字）____ 治愈的奇迹，康复的恩典；',
      '给我们家庭或某人（名字）____ 回头热心的圣宠；',
      '给（名字）____ 伸张正义；',
      '给DJD方济各沙勿略堂早日完工、早日开堂的恩典；',
      '给饱受新冠疫情煎熬的我们整个人类悔改的圣宠及早日战胜这种疫情的恩典力量！',
    ];
    watch(
      () => editKey.value,
      (v) => {
        editValue.value = intentionRef.value[v];
      }
    );

    const isEdit = ref(false);

    function getMyintent() {
      function myIntentClick(event: MouseEvent) {
        visible.value = true;
        event.stopPropagation();
      }
      return (
        <>
          <span onClick={myIntentClick}>
            可自由选择及增加的祈祷意向<i class="icon"></i>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          </span>
        </>
      );
    }

    function getModal() {
      const slots = {
        footer: () => {
          const btnText = unref(isEdit) ? '确定' : '管理';
          const btnClick = unref(isEdit)
            ? () => {
                // appStore.commitMyIntention(intentionRef.value);
                commitMyIntention(intentionRef.value);
                console.log('ok');
                isEdit.value = false;
                // visible.value = false;
              }
            : () => {
                console.log('edit');
                isEdit.value = true;
              };
          return (
            <>
              <Button
                onClick={() => {
                  visible.value = false;
                }}
              >
                关闭
              </Button>
              <Button onClick={btnClick}>{btnText}</Button>
            </>
          );
        },
      };
      return (
        <>
          <Modal
            v-model={[visible.value, 'visible']}
            title="祈祷意向"
            onOk={() => (isEdit.value = true)}
            v-slots={slots}
          >
            {getContent()}
          </Modal>
        </>
      );
    }

    function getContent() {
      function itemClickOk(key: number) {
        if (editKey.value === key) {
          const arr: string[] = [];
          intentionRef.value.forEach((ite) => {
            arr.push(ite);
          });
          arr[key] = editValue.value;
          intentionRef.value = arr;
          editKey.value = -1;
        } else {
          editKey.value = key;
        }
      }
      return (
        <>
          {unref(intentionRef).map((item, key) => {
            return (
              <>
                <span class="iconify" data-icon="emojione:latin-cross" data-inline="false"></span>
                <p>
                  {unref(editKey) === key ? inputItem() : item}
                  {unref(isEdit) ? (
                    <>
                      <Button
                        onClick={() => {
                          itemClickOk(key);
                        }}
                        size="small"
                      >
                        {editKey.value === key ? '确定' : '编辑'}
                      </Button>
                      <Button
                        onClick={() => {
                          const arr: string[] = [];
                          intentionRef.value.forEach((ite) => {
                            arr.push(ite);
                          });
                          arr.splice(key, 1);
                          intentionRef.value = arr;
                          editKey.value = -1;
                        }}
                        size="small"
                        type="danger"
                      >
                        删除
                      </Button>
                    </>
                  ) : null}
                </p>
              </>
            );
          })}
          {unref(isEdit) ? getForm() : null}
        </>
      );
    }

    function inputItem() {
      const isOpen = ref(false);
      return (
        <>
          <Input.TextArea v-model={[editValue.value, 'value']} />
        </>
      );
    }
    const options = ref<{ value: string }[]>(getOption());
    function getOption() {
      return defaultIntention.map((intent) => {
        return {
          value: intent,
        };
      });
    }
    function getForm() {
      const isOpen = ref(false);
      const autoValue = ref('');

      function add() {
        const arr = [];
        intentionRef.value.forEach((ite) => {
          arr.push(ite);
        });
        arr.push(autoValue.value);
        intentionRef.value = arr;
        // intentionRef.value.push(autoValue.value);
      }
      return (
        <>
          <Divider />
          <Input.Group style="display:flex">
            <AutoComplete
              v-model={[autoValue.value, 'value']}
              options={unref(options)}
              onFocus={() => (isOpen.value = true)}
              onSelect={() => (isOpen.value = false)}
              onSearch={() => (isOpen.value = false)}
              defaultOpen={true}
              open={unref(isOpen)}
              style="width:100%"
            />
            <Button onClick={add}>添加</Button>
          </Input.Group>
        </>
      );
    }
    return () => (
      <>
        <span class="tips">
          （ {getMyintent()}）{getModal()}
        </span>
      </>
    );
  },
});
